
#include "cubemap.h"
#include "glext.h"
#include <corona.h>

using namespace WtfEngine;

void CubeMap::Read(const WtfEngine::String &sName) {
	
	int i;
	corona::Image*	vpImage[6];
	
	// load images
	vpImage[0] = corona::OpenImage((sName + ".0.png").c_str(), corona::PF_R8G8B8A8);
	vpImage[1] = corona::OpenImage((sName + ".1.png").c_str(), corona::PF_R8G8B8A8);
	vpImage[2] = corona::OpenImage((sName + ".2.png").c_str(), corona::PF_R8G8B8A8);
	vpImage[3] = corona::OpenImage((sName + ".3.png").c_str(), corona::PF_R8G8B8A8);
	vpImage[4] = corona::OpenImage((sName + ".4.png").c_str(), corona::PF_R8G8B8A8);
	vpImage[5] = corona::OpenImage((sName + ".5.png").c_str(), corona::PF_R8G8B8A8);

	if(!vpImage[0] || !vpImage[1] || !vpImage[2] || !vpImage[3] || !vpImage[4] || !vpImage[5]) {
		for(i = 0; i < 6; i++) {
			if(vpImage[i]) delete vpImage[i];
		};
		throw new std::runtime_error(String("Failed to load cubemap images: ") + sName);
	};

	// load dimensions
	mDim[0] = vpImage[0]->getWidth();
	mDim[1] = vpImage[0]->getHeight() * 6;
	

	// bind and load to gfx mem - and enable filtering
	glGenTextures(1, &mHandle);
	Bind();
	
	for(i = 0; i < 6; i++) {
		glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT + i,
			0, GL_RGBA8, vpImage[i]->getWidth(), vpImage[i]->getHeight(), 0,
			GL_RGBA, GL_UNSIGNED_BYTE, vpImage[i]->getPixels());

		// for square textures, also generate mipmaps
		glTexParameteri(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT + i, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
		gluBuild2DMipmaps(GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT + i, GL_RGBA8, vpImage[i]->getWidth(), vpImage[i]->getHeight(),
						  GL_RGBA, GL_UNSIGNED_BYTE, vpImage[i]->getPixels());
	} 
	Release();

	// clean up
	for(i = 0; i < 6; i++) {
		delete vpImage[i];
	};
	checkGLError("Loaded Texture Image");
};

WtfEngine::IDataObject * CubeMap::Load(const StringPool::Entry& sName) {
	CubeMap * pCubeMap = new CubeMap(sName);
	pCubeMap->Read(sName);
	return pCubeMap;
};
